/*
 * Frågor
 * 1. De vanligaste är BufferedReader+FileReader och Scanner men det finns andra lösningar som är mindra vanliga för att t.ex. läsa xml och windows ini filer
 * 2. new Scanner(File file), t.ex new Scanner(new File("mapdata.map"));
 * 3. Det finns flera sätt t.ex scanner om man vill ha specifika värden t.ex. nummer eller BufferedReader om man vill läsa in en hel fil.
 * 
 */





package exampleOne;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Patrik
 */
public class Main
{

    public static void main(String[] args)
    {
	if (JOptionPane.showConfirmDialog(null, "Do you want to use advanced mode?", "Please select", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
	{
	    new Advanced();
	}
	else
	{
	    try
	    {
		Example.main(new String[0]);
	    }
	    catch (Exception ex)
	    {
		ex.printStackTrace();
		JOptionPane.showMessageDialog(null, "The program has crached with the following exception:\n\n" + ex, "Crash", JOptionPane.ERROR_MESSAGE);
		System.exit(14);
	    }
	}
    }

}

class Example
{
    public static void main(String[] arg)throws IOException{
	// Skapa en scanner som läser från filen
	Scanner sc = new Scanner(new File("data.txt"));
	int sum = 0;
	while (sc.hasNextInt()) {
	    int i = sc.nextInt();
	    sum += i;
	}
    }
}

class Advanced
{
    public Advanced()
    {
	JFileChooser chooser = new JFileChooser();

	if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
	{
	    System.exit(0);
	}

	File file = chooser.getSelectedFile();

	if (!file.exists())
	{
	    JOptionPane.showMessageDialog(null, "Coult not find " + file.getName() + "!", "Error", JOptionPane.ERROR_MESSAGE);
	    System.exit(11);
	}
	if (!file.canRead())
	{
	    JOptionPane.showMessageDialog(null, "Could not read " + file.getName() + "!", "Error", JOptionPane.ERROR_MESSAGE);
	    System.exit(12);
	}

	try
	{
	    Scanner sc = new Scanner(file);
	    String res = "";

	    int sum = 0;
	    int num = 0;

	    while(sc.hasNextInt())
	    {
		int next = sc.nextInt();
		res += next + ", ";
		sum += next;
		num++;
	    }
	    if (res.length() > 0) // Kör bara om den hittat något
	    {
		res = res.substring(0, res.length() - 2);
	    }
	    JOptionPane.showMessageDialog(null, num + " numbers was found:\n" + res + "\n\nThe sum of the numbers is " + sum, "Results", JOptionPane.PLAIN_MESSAGE);
	    System.exit(0);
	}
	catch (Exception ex)
	{
	    ex.printStackTrace();
	    JOptionPane.showMessageDialog(null, "The program has crached with the following exception:\n\n" + ex, "Crash", JOptionPane.ERROR_MESSAGE);
	    System.exit(13);
	}
    }
}